package org.example.skytool.security;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.BCrypt;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

public class EncoderUtil {

    public static String encode(String password) {
        // 随机盐值
        String salt = IdUtil.simpleUUID();
        // 密码（md5(随机盐值+密码)）
        String finalPassword = SecureUtil.md5(salt + password);
        return salt + "$" + finalPassword;
    }


    /**
     * 解密
     */
    public static boolean match(String password, String securePassword) {
        boolean result = false;
        if (StringUtils.hasLength(password) && StringUtils.hasLength(securePassword)) {
            if (securePassword.length() == 65 && securePassword.contains("$")) {
                String[] securePasswordArr = securePassword.split("\\$");
                String slat = securePasswordArr[0];
                String finalPassword = securePasswordArr[1];
                password = SecureUtil.md5(slat + password);
                if (finalPassword.equals(password)) {
                    result = true;
                }
            }
        }
        return result;
    }

}